//! 处理流数据

use std::{
    fs,
    io::{BufRead, BufReader, Write},
    net::TcpStream,
};

/// 处理一个请求，从请求中读取数据
///
/// - stream: 请求数据的封装对象
pub fn handle_connection(mut stream: TcpStream) {
    // 缓冲区读取器，用于优化对底层数据源（如文件、网络流等）的读取操作
    let buf_reader: BufReader<&mut TcpStream> = BufReader::new(&mut stream);
    let http_request: Vec<_> = buf_reader
        .lines() // 获取迭代器，按行迭代读取
        .map(|result| result.unwrap())
        .take_while(|line| !line.is_empty()) // 从迭代器中获取元素 直到不满足要求为止
        .collect();
    println!("Request: {:#?}", http_request);

    // 分情况处理，读首行判断请求状态
    let request_line = &http_request[0]; // 请求首行

    let (status_line, filename) = if request_line == "GET / HTTP/1.1" {
        ("HTTP/1.1 200 OK", "response.html")
    } else {
        ("HTTP/1.1 404 NOT FOUND", "404.html")
    };

    // 处理应答
    let contents = fs::read_to_string("./src/resources/".to_string() + filename).unwrap();
    let length = contents.len();
    let response = format!("{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}");

    // 本请求的响应写入
    stream
        .write_all(response.as_bytes())
        .expect("write response fail");
    stream.flush().unwrap(); // 立即刷写
}
